# A simple test for Linux Frame Buffer
# Imports fb (frame buffer) module and uses it as lvgl display driver
# Registers mouse evdev and shows line cursor
# then shows a button on screen.
import usys as sys
sys.path.append('')
sys.path.append('./driver')

import lvgl as lv
import time
import evdev

class ColorStyle(lv.style_t):
    def __init__(self, color):
        super().__init__()
        self.set_bg_opa(lv.STATE.DEFAULT, lv.OPA.COVER);
        self.set_bg_color(lv.STATE.DEFAULT, lv.color_hex3(color))
        #self.set_bg_grad_color(lv.STATE.DEFAULT, lv.color_hex3(0xFFF));
        #self.set_bg_grad_dir(lv.STATE.DEFAULT, lv.GRAD_DIR.VER);

        #self.set_bg_main_stop(lv.STATE.DEFAULT, 0);
        #self.set_bg_grad_stop(lv.STATE.DEFAULT, 128);

lv.init()


# Register FB display driver
import fb
fb.init()

#event_loop = lv_utils.event_loop(freq = 60, asynchronous=True)

# Register  FB display driver
LCD_W = 720 #240
LCD_H = 1280 #320
disp_buf1 = lv.disp_draw_buf_t()
buf1_1 = bytes(LCD_W*LCD_H//10)
#buf1_2 = bytes(LCD_W*10)
disp_buf1.init(buf1_1, None, len(buf1_1)//4)
disp_drv = lv.disp_drv_t()
disp_drv.init()
disp_drv.draw_buf = disp_buf1
disp_drv.flush_cb = fb.flush
disp_drv.hor_res = LCD_W
disp_drv.ver_res = LCD_H
disp_drv.register()

# Create a screen and a button

def event_handler(evt):
    print("Clicked event seen")


scr = lv.obj()
scr.clear_flag(scr.FLAG.SCROLLABLE) #关闭滚动效果

# 主界面背景颜色设置
#scr_style = ColorStyle(0x000)             rgb
#scr.add_style(scr.PART.MAIN, scr_style)# brg
#scr.set_style_local_bg_color(scr.PART.MAIN, lv.STATE.DEFAULT, lv.color_hex3(0x020))

btn = lv.btn(scr)
#btn.set_size(64,20)
btn.align(lv.ALIGN.CENTER, 0, 0) #IN_TOP_LEFT
label = lv.label(btn)
label.set_text("Hello")
btn.add_event_cb(event_handler,lv.EVENT.CLICKED, None)

# load png img
import fs_driver
fs_drv = lv.fs_drv_t()
fs_driver.fs_register(fs_drv, 'S')
img = lv.img(scr)
img.set_src("S:../assets/App.png")
img.align(lv.ALIGN.TOP_LEFT, 20, 20)

# Regiser mouse device and crosshair cursor

# mouse = evdev.mouse_indev(scr)
# mouse = evdev.tp_indev(scr,device='/dev/input/event2')

# regiser tp
import touchscreen
#touchscreen.init(device='/dev/input/event2',width=720,height=1280)
if touchscreen.init('/dev/input/event2'):
    indev_drv = lv.indev_drv_t()
    indev_drv.init()
    indev_drv.type = lv.INDEV_TYPE.POINTER
    indev_drv.read_cb = touchscreen.tp_read
    indev_drv.register()

# Load the screen

lv.scr_load(scr)

if __name__ == '__main__':
    while True:
        time.sleep_ms(1000)
        #lv.scr_load(scr)
        pass